<template>
  <dv-charts :option="option" />
</template>

<script>
import { changeDefaultConfig } from '@jiaminghi/charts'

export default {
  name: 'BarChart',
  props: {
    chartsBarData: {
      type: Object,
      required: true
    },
    // 是否显示数值标签
    labelIsShow: {
      type: Boolean,
      required: false,
      default: false
    },
    // 是否显示图例
    legendIsShow: {
      type: Boolean,
      required: false,
      default: false
    },
    // 是否堆叠显示
    isStack: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data () {
    return {
      option: {}
    }
  },
  methods: {
    createChart () {
      // 修改默认配置
      changeDefaultConfig('xAxis', this.$utils.chartsDefaultOptions.xAxisParam)
      changeDefaultConfig('yAxis', this.$utils.chartsDefaultOptions.yAxisParam)
      // 循环数据，取出图例legend下的data数据
      const _legendData = []
      this.chartsBarData.legend.forEach((item) => {
        _legendData.push({
          name: item
        })
      })
      // console.log(_legendData)
      // 循环数据，取出series下的data数据
      const _series = []
      this.chartsBarData.series.forEach((item, index) => {
        // 根据参数判断stack类型
        if (this.isStack) {
          _series.push({
            name: this.chartsBarData.legend[index],
            data: item,
            type: 'bar',
            stack: 'a', // 可以是任何字符串。
            independentColor: '#ffffff',
            label: {
              show: this.labelIsShow,
              position: 'center'
            }
          })
        } else {
          _series.push({
            name: this.chartsBarData.legend[index],
            data: item,
            type: 'bar',
            stack: index,
            label: {
              show: this.labelIsShow,
              position: 'center'
            }
          })
        }
      })
      this.option = {
        legend: {
          show: this.legendIsShow,
          textStyle: {
            fill: '#ccc'
          },
          data: _legendData
        },
        xAxis: {
          data: this.chartsBarData.xAxis
        },
        yAxis: {
          data: 'value'
        },
        series: _series
      }
    }
  },
  watch: {
    chartsBarData: {
      handler (newValue, oldValue) {
        if (oldValue != newValue) {
          this.createChart()
        }
      },
      deep: true
    }
  }
}
</script>

<style>
/* .dv-charts-container {
  height: calc(100% - 50px);
} */
</style>
